package com.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * 说明：心跳服务器
 *
 */
public final class HeartbeatServer {

	static final int PORT = 8082;

	private Thread thread;

	public void start() {
		thread = new Thread() {
			@Override
			public void run() {
				// Configure the server.
				EventLoopGroup bossGroup = new NioEventLoopGroup(1);
				EventLoopGroup workerGroup = new NioEventLoopGroup();
				try {
					ServerBootstrap b = new ServerBootstrap();
					b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
							.option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO))
							.childHandler(new HeartbeatHandlerInitializer());

					// Start the server.
					ChannelFuture f = b.bind(PORT).sync();

					// Wait until the server socket is closed.
					f.channel().closeFuture().sync();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					// Shut down all event loops to terminate all threads.
					bossGroup.shutdownGracefully();
					workerGroup.shutdownGracefully();
				}
			}

		};
		// thread.setDaemon(true);
		thread.start();
	}
}
